<template>
    <div>
        <!-- 商品列表展示区域 -->
        <div v-show="activeStatu">
            <el-card class="box">
                <div class="container-padding">
                    <!-- 搜索和筛选区域 -->
                    <div class="flex">
                        <div class="category-title">分类标题</div>
                        <div class="time_top">创建时间</div>
                    </div>
                    <div class="flexBox">
                        <div>
                            <!-- 商品名称搜索框 -->
                            <el-input v-model.trim="inputed" @input="filters" placeholder="输入标题" class="search-input">
                                <template #prefix>
                                    <el-icon class="el-input__icon">
                                        <search />
                                    </el-icon>
                                </template>
                            </el-input>
                        </div>
                        <div class="date-picker-container">
                            <!-- 日期范围选择器 -->
                            <el-date-picker @change="data_filters" v-model="time" type="daterange"
                                range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期" />
                        </div>
                    </div>
                    <div class="button-group">
                        <div><el-button type="primary" @click="add" class="add_class">
                                新增</el-button>
                        </div>
                        <el-button type="danger" class="delelist" @click="deleList">批量删除</el-button>
                    </div>
                    
                    <!-- 商品表格展示区域 -->
                    <div>
                        <el-table :data="activeList.slice((currentPage - 1) * pageSize, currentPage * pageSize)"
                            class="商品表格" :cell-style="{ 'text-align': 'center' }" lazy="true"
                            v-el-table-infinite-scroll="handleTableScroll"
                            :header-cell-style="{ 'text-align': 'center' }" @selection-change="handleSelectionChange"
                            height="auto">
                            <el-table-column type="selection" fixed="left" />
                            <el-table-column prop="id" width="110px" label="序号" fixed="left" />
                            <el-table-column prop="shoptitle" label="店铺名称" show-overflow-tooltip width="140" />
                            <el-table-column prop="title" label="商品名称" show-overflow-tooltip width="140" />
                            <el-table-column prop="desc" width="200" label="介绍" show-overflow-tooltip />
                            <el-table-column prop="quantity" label="销售量" show-overflow-tooltip width="100" sortable />
                            <el-table-column prop="status" label="上架/下架" width="120">
                                <template #default="scope">
                                    <!-- 商品状态切换开关 -->
                                    <el-switch @click="funstatus(scope.row)"
                                        :model-value="scope.row.status == 1 ? true : scope.row.status == 0 ? false : scope.row.status"
                                        inline-prompt />
                                </template>
                            </el-table-column>
                            <el-table-column prop="price" width="120" label="价格" sortable show-overflow-tooltip />
                            <el-table-column prop="userImg" label="图片" width="80">
                                <template #default="scope">
                                    <!-- 商品图片预览 -->
                                    <div class="demo-image__preview">
                                        <el-image class="product-image" :src="testName + scope.row.img"
                                            :zoom-rate="1.2" :max-scale="7" :min-scale="0.2" :preview-src-list="[testName +
                                                scope.row.img]" :initial-index="4" fit="cover" preview-teleported />
                                    </div>
                                </template>
                            </el-table-column>
                            <el-table-column prop="createtime" label="创建时间" width="200" show-overflow-tooltip />
                            <el-table-column label="操作" width="100" fixed="right">
                                <template #default="scope">
                                    <!-- 编辑和删除操作按钮 -->
                                    <div class="handle">
                                        <div @click="edit(scope.row)" class="edit-btn">编辑</div>
                                        <div class="handle-separator"></div>
                                        <div @click="deletes(scope.row)" class="delete-btn">删除</div>
                                    </div>
                                </template>
                            </el-table-column>
                        </el-table>
                    </div>

                    <!-- 分页控件 -->
                    <div class="paging">
                        <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize"
                            :page-sizes="[5, 10, 20, 50]" :small="small" :disabled="disabled" background
                            layout="total, sizes, prev, pager, next, jumper" :total="activeList.length" />
                    </div>
                    
                    <!-- 删除确认对话框 -->
                    <el-dialog title="删除" v-model="centerDialogVisible" width="30%" center>
                        <div class="dialog-message">确认删除该数据吗?</div>
                        <div class="dialog-footer">
                            <el-button @click="centerDialogVisible = false">取 消</el-button>
                            <el-button type="primary" @click="deleteid">确 定</el-button>
                        </div>
                    </el-dialog>
                </div>
                <!-- 批量删除确认对话框 -->
                <el-dialog v-model="shows" title="是否要删除" center width="20vw">
                    <el-button @click="shows = false">取 消</el-button>
                    <el-button type="primary" @click="oks">确 定</el-button>
                </el-dialog>
                <!-- 批量删除确认对话框 -->
                <el-dialog title="批量删除" v-model="centerDialogVisiblet" width="30%" center>
                    <div class="dialog-message">确认删除这批数据吗?</div>
                    <span slot="footer" class="dialog-footer">
                        <div></div>
                        <div>
                            <el-button @click="centerDialogVisiblet = false">取 消</el-button>
                            <el-button type="primary" @click="deleteid_t">确 定</el-button>
                        </div>
                    </span>
                </el-dialog>
            </el-card>
        </div>
        
        <!-- 新增/编辑商品表单区域 -->
        <div v-show="activeStatud" class="form-container">
            <el-card class="form-card">
                <div class="form-title">{{ addText }}</div>
                <div class="divider"></div>
                <div class="form-content">
                    <!-- 商品表单 -->
                    <el-form ref="ruleFormRef" class="商品表单" :model="ruleForm"
                        status-icon :rules="rules" label-position="left" label-width="auto" >
                        <div class="form-row">
                            <div class="form-column">
                                <!-- 选择店铺下拉框 -->
                                <el-form-item label="选择店铺" prop="foodshop_id" class="form-item">
                                    <el-select v-model="ruleForm.foodshop_id" placeholder="请选择" 
                                        clearable :disabled="activess">
                                        <el-option v-for="item in optiond" :key="item.value" :label="item.label"
                                            :value="item.value" />
                                    </el-select>
                                </el-form-item>
                                <!-- 选择分类下拉框 -->
                                <el-form-item label="选择分类" prop="foodproducttype_id" class="form-item">
                                    <el-select v-model="ruleForm.foodproducttype_id" placeholder="请选择分类">
                                        <el-option v-for="item in optionss" :key="item.value" :label="item.label"
                                            :value="item.value" />
                                    </el-select>
                                </el-form-item>
                                <!-- 商品名称输入框 -->
                                <el-form-item label="商品名称" prop="title" class="form-item">
                                    <el-input v-model.trim="ruleForm.title" placeholder="请输入" 
                                        @blur="checkProductName" />
                                </el-form-item>
                                <!-- 商品图片上传 -->
                                <el-form-item prop="img" label="海报" class="form-item image-upload">
                                    <el-upload list-type="picture-card" v-model="ruleForm.img"
                                        :on-preview="handlePictureCardPreview" :on-remove="handleRemove"
                                        :file-list="fileList" accept=".jpeg,.png,.jpg,.bmp,.gif" max="1" ref="uploadEle"
                                        :on-change="handleChange" :on-success="handleSuccess"
                                        :before-upload="beforeUpload" multiple>
                                        <el-icon>
                                            <Plus />
                                        </el-icon>
                                    </el-upload>
                                    <el-dialog v-model="dialogVisible">
                                        <img width="90%" :src="dialogImageUrl" alt="" />
                                    </el-dialog>
                                </el-form-item>
                            </div>
                            <div class="form-column right-column">
                                <!-- 商品描述输入框 -->
                                <el-form-item label="商品说明" prop="desc" class="form-item">
                                    <el-input v-model.trim="ruleForm.desc" maxlength="200" 
                                        placeholder="请输入" show-word-limit type="textarea"
                                        :autosize="{ minRows: 3, maxRows: 5 }" />
                                </el-form-item>
                                <!-- 商品原价输入框 -->
                                <el-form-item label="商品原价" prop="old_price" class="form-item">
                                    <div class="custom-number-input">
                                        <button type="button" @click="decreaseOldPrice">-</button>
                                        <input type="text" v-model="ruleForm.old_price" @input="handleOldPriceInput"
                                            @blur="validateOldPriceInput" />
                                        <button type="button" @click="increaseOldPrice">+</button>
                                    </div>
                                </el-form-item>
                                <!-- 商品销量输入框 -->
                                <el-form-item label="销量" prop="quantity" class="form-item">
                                    <div class="custom-number-input">
                                        <button type="button" @click="decreaseQuantity">-</button>
                                        <input type="text" v-model="ruleForm.quantity" @input="handleQuantityInput"
                                            @blur="validateQuantityInput" />
                                        <button type="button" @click="increaseQuantity">+</button>
                                    </div>
                                </el-form-item>
                                <!-- 商品现价输入框 -->
                                <el-form-item label="商品现价" prop="price" class="form-item">
                                    <div class="custom-number-input">
                                        <button type="button" @click="decreasePrice">-</button>
                                        <input type="text" v-model="ruleForm.price" @input="handlePriceInput"
                                            @blur="validatePriceInput" />
                                        <button type="button" @click="increasePrice">+</button>
                                    </div>
                                </el-form-item>
                                <!-- 商品状态开关 -->
                                <el-form-item prop="status" label="上架下架" class="form-item">
                                    <el-switch v-model="ruleForm.status" />
                                </el-form-item>
                            </div>
                        </div>
                        <!-- 百度富文本编辑器区域 -->
                    </el-form>
                    <div class="dialog-footer form-actions">
                        <el-button type="primary" @click="submitForm(ruleFormRef)">确认</el-button>
                        <el-button @click="closes(ruleFormRef)">取消</el-button>
                    </div>
                </div>
            </el-card>
        </div>
    </div>
</template>

<script setup>
import { ref, reactive, watch } from 'vue';
// 导入商品相关API
import { foodList } from '../../../api/food/index'
import { food_shopList } from '../../../api/foodShop/index'
import { food_productList, food_productChange, food_productSave, food_productDel, } from '../../../api/foodproduct/index'
import { ElMessage, ElCard } from 'element-plus';
// 导入图片上传API
import { scenicUpload } from '../../../api/uploading/index';

// 搜索和筛选相关数据
const time = ref('')
const options = ref([])
// 商品列表数据
const activeList = ref([]);
// 控制视图显示状态
const activeStatu = ref(true)
const activeStatud = ref(false)
// 注入全局函数和变量
import { inject } from 'vue'
const testFn = inject('testFn')
testFn()
const testName = inject('testName')
// 对话框显示控制
const dialogTableVisible = ref(false);
const statused = ref('1');
const activess = ref()
// 表格分页控制
const inputed = ref('');
const pageSize = ref(5);
const currentPage = ref(1);
const copyList = ref([]);
const files = ref(false);
// 选项数据
const optionss = ref([])
const optiond = ref([])
// 获取用户认证信息
let tokens = JSON.parse(localStorage.getItem('tokens'));
console.log(tokens);
const filter_list = ref([])
// 商品名称查重相关
const originalProductName = ref('')
const productNameExists = ref(false)

// 页面加载时初始化渲染
render();
// 获取商品列表和选项数据
function render() {
    food_productList({
        token: tokens.token,
        uid: tokens.userinfo.id
    }).then((res) => {
        console.log(res);
        activeList.value = res.data;
        copyList.value = res.data;
        filter_list.value = res.data
        options.value = filter_list.value
    });
    // 获取分类选项数据
    foodList().then((res) => {
        let array = []
        console.log(res);
        for (let i = 0; i < res.data.length; i++) {
            let obj = {
                label: res.data[i].title,
                value: String(res.data[i].id) // 确保value是字符串类型
            }
            array.push(obj)
        }
        optionss.value = array
    });
    // 获取店铺选项数据
    food_shopList({
        token: tokens.token,
        uid: tokens.userinfo.id
    }, {
        userid: tokens.userinfo.id
    }).then((res) => {
        let array = []
        console.log(res);
        for (let i = 0; i < res.data.length; i++) {
            let obj = {
                label: res.data[i].title,
                value: res.data[i].id
            }
            array.push(obj)
        }
        optiond.value = array
    });
}

const statust = ref('')
// 切换商品上架/下架状态
function funstatus(e) {
    console.log(e);

    if (e.status == 1) {
        statust.value = 0;
    } else if (e.status == 0) {
        statust.value = 1;
    }

    food_productChange(
        {
            ids: e.id,
            status: statust.value,
            uid: e.foodproducttype_id
        }
    ).then((res) => {
        if (res.code == 1) {
            ElMessage({
                message: '操作成功',
                type: 'success',
            });
            render();
        } else if (res.code == 0) {
            ElMessage({
                message: '状态不能和上一次一致',
                type: 'warning',
            });
        }
    });
}

// 日期筛选处理函数
const data_filters = () => {
    let end_time
    let start_time
    let ars = []
    if (time.value) {
        end_time = Date.parse(new Date(time.value[0]))
        start_time = Date.parse(new Date(time.value[1]))
    }
    activeList.value = copyList.value.filter((item) => {
        if (item.title ?
            item.title.indexOf(inputed.value) > -1 &&
            (time.value ?
                Date.parse(new Date(`${item.createtime}`)) > end_time &&
                Date.parse(new Date(` ${item.createtime}`)) < start_time : true
            ) : true
        ) {
            return item
        }
        ars.push(item)
        // console.log(item);
    });
}

// 编辑器配置（百度富文本）
const editorConfig = reactive({
    // 编辑器不自动被内容撑高
    autoHeightEnabled: false,
    // 初始容器高度
    initialFrameHeight: 200,
    // 初始容器宽度
    initialFrameWidth: '100vw',
    UEDITOR_HOME_URL: '/UEditor/', // 访问 UEditor 静态资源的根路径，可参考常见问题1
    serverUrl: '/pc/common/ueditor', // 服务端接⼝
    uploadUrl: '/UEditor',
    // enableAutoSave: true, // 开启从草稿箱恢复功能需要⼿动设置固定的 editorId，否则组件会默认随机⼀个，如果页⾯刷新，下次渲染的时候 editorId 会重新随机，// 服务端接口（这个地址是我为了方便各位体验文件上传功能搭建的临时接口，请勿在生产环境使用！！！）
});

// 表单数据对象
const ruleForms = reactive({
    title: '',
    img: '',
    desc: '',
    price: '',
    old_price: '',
    foodproducttype_id: '',
    foodshop_id: '',
    quantity: '',
    status: false
})

// 图片上传相关
const fileList = ref([])
// 图片上传前处理
const beforeUpload = (file) => {
    const formData = new FormData();
    formData.append('file', file);
    scenicUpload(formData).then((res) => {
        console.log(res);
        fileList.value = [
            {
                url: testName + res.data.url,
            },
        ];
        imgUrls.value = res.data.url;
        ruleForm.img = res.data.url;
        console.log(ruleForm);
    })

    return false; // 阻止默认上传行为
    // 在这里可以添加文件上传前的验证逻辑
};

// 新增商品处理
const addText = ref("")
function add() {
    activeStatu.value = false
    addText.value = '添加'
    activess.value = false
    activeStatud.value = true
    dialogTableVisible.value = true;
    statused.value = '1';
    disableds.value = true;
    // 重置表单数据
    (ruleForm.name = ''), (ruleForm.start_time = ''), (ruleForm.end_time = ''), (ruleForm.details = ''), (ruleForm.img = ''), (ruleForm.synopsis = '');

    // 重置查重相关状态
    originalProductName.value = ''
    productNameExists.value = false
}

// 表单数据
const ruleForm = reactive({
    title: '',
    img: '',
    desc: '',
    price: '',
    old_price: '',
    foodproducttype_id: '',
    foodshop_id: '',
    quantity: '',
    status: false
});

// 表单引用和验证规则
const ruleFormRef = ref('');
const rules = reactive({
    title: [
        {
            required: true,
            message: '请输入商品名称',
            trigger: 'blur',
        },
        {
            validator: (rule, value, callback) => {
                if (productNameExists.value) {
                    callback(new Error('商品名称已存在'))
                } else {
                    callback()
                }
            },
            trigger: 'blur'
        }
    ],
    desc: [
        {
            required: true,
            message: '请输入商品说明',
            trigger: 'blur',
        },
    ],
    price: [
        {
            required: true,
            message: '请输入商品现价',
            trigger: 'blur',
        },
        {
            validator: (rule, value, callback) => {
                // 验证是否为正数（可以是小数）
                if (!value) {
                    callback(new Error('请输入商品现价'))
                } else if (isNaN(parseFloat(value)) || parseFloat(value) <= 0) {
                    callback(new Error('请输入大于0的数字'))
                } else {
                    callback()
                }
            },
            trigger: 'blur'
        }
    ],
    old_price: [
        {
            required: true,
            message: '请输入商品原价',
            trigger: 'blur',
        },
        {
            validator: (rule, value, callback) => {
                // 验证是否为正数（可以是小数）
                if (!value) {
                    callback(new Error('请输入商品原价'))
                } else if (isNaN(parseFloat(value)) || parseFloat(value) <= 0) {
                    callback(new Error('请输入大于0的数字'))
                } else {
                    callback()
                }
            },
            trigger: 'blur'
        }
    ],
    img: [
        {
            required: true,
            message: '请上传图片',
            trigger: 'blur',
        },
    ],
    foodproducttype_id: [
        {
            required: true,
            message: '请选择分类',
            trigger: 'blur',
        },
    ],
    quantity: [
        {
            required: true,
            message: '请输入销量',
            trigger: 'blur',
        },
        {
            validator: (rule, value, callback) => {
                // 验证是否为正整数
                if (!value) {
                    callback(new Error('请输入销量'))
                } else if (!/^[1-9]\d*$/.test(value)) {
                    callback(new Error('请输入大于0的正整数'))
                } else {
                    callback()
                }
            },
            trigger: 'blur'
        }
    ],
    foodshop_id: [
        {
            required: true,
            message: '请选择店铺',
            trigger: 'blur',
        },
    ]
});

// 时间验证函数
function validateEmailDomain(rule, value, callback) {
    if (value === '') {
        callback(new Error('结束时间不能为空'));
    } else if (value < ruleForm.start_time) {
        // 假设我们只允许 @example.com 的邮箱  
        callback(new Error('结束时间不能小于开始时间'));
    } else {
        callback();
    }
}

// 图片URL
const imgUrls = ref('');

// 商品名称查重函数
function checkProductName() {
    const currentName = ruleForm.title.trim()

    // 如果名称为空，不进行查重
    if (!currentName) {
        productNameExists.value = false
        return
    }

    // 编辑状态下，如果名称没有变化，不进行查重
    if (statused.value === '2' && currentName === originalProductName.value) {
        productNameExists.value = false
        return
    }

    // 检查本地数据中是否存在相同名称的商品
    const exists = activeList.value.some(item => {
        return item.title.trim() === currentName
    })

    productNameExists.value = exists

    if (exists) {
        ElMessage({
            message: '商品名称已存在',
            type: 'warning'
        })
    }
}

// 提交表单（新增或编辑）
const submitForm = (formEl) => {
    console.log(ruleForm);
    if (!formEl) return;
    formEl.validate((valid) => {
        if (valid) {
            // 额外检查商品名称是否已存在
            if (productNameExists.value) {
                ElMessage({
                    message: '商品名称已存在',
                    type: 'error'
                })
                return
            }

            if (statused.value == '1') {
                console.log(ruleForm);
                ruleForm.uid = tokens.userinfo.id
                if (ruleForm.status == true) {
                    ruleForm.state = '1'
                }
                else {
                    ruleForm.status = '2'
                }
                // 调用新增商品API
                food_productSave(ruleForm).then((res) => {
                    if (res.code == '1') {

                        ElMessage({
                            message: '新增成功',
                            type: 'success',
                        });
                        setTimeout(() => {
                            activeStatud.value = false;
                            activeStatu.value = true;
                        }, 1200);
                        closes(ruleFormRef.value)
                        render();
                    }
                    Object.assign(ruleForm, ruleForms)
                    ruleFormRef.value.$resetFields();
                });
            } else if (statused.value == '2') {
                ruleForm.id = ids.value
                ruleForm.uid = tokens.userinfo.id

                if (ruleForm.status == true) {
                    ruleForm.state = '1'
                }
                else {
                    ruleForm.status = '2'
                }
                // 调用编辑商品API
                food_productSave(ruleForm).then((res) => {
                    if (res.code == '1') {

                        ElMessage({
                            message: '编辑成功',
                            type: 'success',
                        });
                        setTimeout(() => {
                            activeStatud.value = false;
                            activeStatu.value = true;
                        }, 1200);
                        closes(ruleFormRef.value)
                        render();
                    } else if (res.msg == '编辑失败') {
                        ElMessage({
                            message: '编辑失败，不能和原数据一致',
                            type: 'warning',
                        });
                    } else {

                    }
                });
            }
        }
        else {
            ElMessage({
                message: '表单验证失败',
                type: 'error',
            });
        }
    });
};

// 当前操作的商品ID
const ids = ref('');
const disableds = ref(true);
// 关闭表单
const closes = (formEl) => {
    console.log(formEl);
    activeStatu.value = true
    activeStatud.value = false
    formEl.resetFields();
    formEl.clearValidate()
    dialogTableVisible.value = false;
    files.value = false;
    ruleForm.name = ''
    ruleForm.img = ''
    fileList.value = [

    ];

    // 重置查重相关状态
    originalProductName.value = ''
    productNameExists.value = false
};

// 编辑商品
function edit(item) {
    console.log(item);
    activess.value = true
    // 填充表单数据
    Object.assign(ruleForm, item);

    // 确保分类ID以正确格式设置
    ruleForm.foodproducttype_id = String(item.foodproducttype_id);

    console.log(ruleForm.img);
    fileList.value = [
        {
            url: testName + item.img,
        },
    ];
    ruleForm.status = item.status == 1 ? true : false
    addText.value = '编辑'
    ids.value = item.id;
    activeStatud.value = true
    activeStatu.value = false
    ruleForm.name = item.title
    disableds.value = false;
    statused.value = '2';

    // 记录原始商品名称，用于查重时比较
    originalProductName.value = item.title.trim()
    productNameExists.value = false
}

// 删除商品
function deletes(item) {
    console.log(item);
    centerDialogVisible.value = true;
    deleteids.value = item.id;
}

// 待删除的商品ID
const deleteids = ref('');
const centerDialogVisible = ref(false);

// 确认删除商品
function deleteid() {
    food_productDel(
        {
            ids: deleteids.value,
            uid: tokens.userinfo.id
        }
    ).then((res) => {
        if (res.code == '1') {
            centerDialogVisible.value = false;
            ElMessage({
                message: '删除成功',
                type: 'success',
            });
            render();
        }
    });
}

// 商品名称搜索过滤
function filters() {
    currentPage.value = 1
    console.log(inputed.value);
    let a = [];
    activeList.value = copyList.value.filter(function (item) {
        // 判断是否满足搜索条件
        if (String(item.title).indexOf(String(inputed.value)) > -1) {
            return a;
        }
    });
    currentPage.value = 1
}

// 批量操作相关
const shows = ref(false);
// 已选择的商品
const SelectArr = ref([])
const All_Delete = ref([])
// 表格选择变化处理
const handleSelectionChange = (val) => {
    All_Delete.value = []
    SelectArr.value = val
    SelectArr.value.forEach(item => {
        console.log(item);
        All_Delete.value.push(item.id)
    })
    console.log(All_Delete.value);
}

// 批量删除处理
const centerDialogVisiblet = ref(false)
const st = ref([])
function deleList() {
    st.value = []
    console.log(All_Delete.value);
    st.value.push(All_Delete.value)
    if (All_Delete.value == '') {
        ElMessage({
            message: '请勾选要删除的数据',
            type: 'warning',
        })
    } else {
        centerDialogVisiblet.value = true
    }
}

// 确认批量删除
const deleteid_t = () => {
    food_productDel({
        ids: st.value.join(','),
        uid: tokens.userinfo.id
    }).then(res => {
        console.log(res, '删除成功或失败回调');
        centerDialogVisiblet.value = false;
        render();
        ElMessage({
            message: '删除成功',
            type: 'success',
        })
    })
}

// 销量增减控制
const decreaseQuantity = () => {
    if (ruleForm.quantity && parseInt(ruleForm.quantity) > 1) {
        ruleForm.quantity = (parseInt(ruleForm.quantity) - 1).toString();
    }
};

const increaseQuantity = () => {
    if (ruleForm.quantity) {
        ruleForm.quantity = (parseInt(ruleForm.quantity) + 1).toString();
    } else {
        ruleForm.quantity = '1';
    }
};

// 原价增减控制
const decreaseOldPrice = () => {
    if (ruleForm.old_price && parseFloat(ruleForm.old_price) > 0.1) {
        ruleForm.old_price = (parseFloat(ruleForm.old_price) - 0.1).toFixed(1);
    }
};

const increaseOldPrice = () => {
    if (ruleForm.old_price) {
        ruleForm.old_price = (parseFloat(ruleForm.old_price) + 0.1).toFixed(1);
    } else {
        ruleForm.old_price = '0.1';
    }
};

// 现价增减控制
const decreasePrice = () => {
    if (ruleForm.price && parseFloat(ruleForm.price) > 0.1) {
        ruleForm.price = (parseFloat(ruleForm.price) - 0.1).toFixed(1);
    }
};

const increasePrice = () => {
    if (ruleForm.price) {
        ruleForm.price = (parseFloat(ruleForm.price) + 0.1).toFixed(1);
    } else {
        ruleForm.price = '0.1';
    }
};

// 销量验证函数
const validateQuantity = (rule, value, callback) => {
    // 定义正整数正则表达式（不允许前导零）
    const reg = /^[1-9]\d*$/;

    if (!value) {
        callback(new Error('请输入销量'));
    } else if (!reg.test(value)) {
        callback(new Error('请输入大于0的正整数'));
    } else {
        callback();
    }
};

// 原价验证函数
const validateOldPrice = (rule, value, callback) => {
    // 定义正数正则表达式（可以是小数）
    const reg = /^\d+(\.\d{1,2})?$/;

    if (!value) {
        callback(new Error('请输入商品原价'));
    } else if (!reg.test(value) || parseFloat(value) <= 0) {
        callback(new Error('请输入大于0的数字'));
    } else {
        callback();
    }
};

// 现价验证函数
const validatePrice = (rule, value, callback) => {
    // 定义正数正则表达式（可以是小数）
    const reg = /^\d+(\.\d{1,2})?$/;

    if (!value) {
        callback(new Error('请输入商品现价'));
    } else if (!reg.test(value) || parseFloat(value) <= 0) {
        callback(new Error('请输入大于0的数字'));
    } else {
        callback();
    }
};

// 销量输入处理
const handleQuantityInput = (event) => {
    // 获取输入值
    let value = event.target.value;

    // 过滤非数字字符
    value = value.replace(/[^0-9]/g, '');

    // 不允许前导零（除非是单个0，但我们的规则是大于0的正整数）
    if (value.startsWith('0') && value.length > 1) {
        value = value.substring(1);
    }

    // 更新Vue数据
    ruleForm.quantity = value;
};

// 原价输入处理
const handleOldPriceInput = (event) => {
    // 获取输入值
    let value = event.target.value;

    // 过滤非数字和小数点字符
    value = value.replace(/[^0-9.]/g, '');

    // 确保最多只有一个小数点
    const parts = value.split('.');
    if (parts.length > 2) {
        value = parts[0] + '.' + parts[1];
    }

    // 更新Vue数据
    ruleForm.old_price = value;
};

// 现价输入处理
const handlePriceInput = (event) => {
    // 获取输入值
    let value = event.target.value;

    // 过滤非数字和小数点字符
    value = value.replace(/[^0-9.]/g, '');

    // 确保最多只有一个小数点
    const parts = value.split('.');
    if (parts.length > 2) {
        value = parts[0] + '.' + parts[1];
    }

    // 更新Vue数据
    ruleForm.price = value;
};

// 销量失焦验证
const validateQuantityInput = () => {
    const value = ruleForm.quantity;
    const reg = /^[1-9]\d*$/;

    if (value && !reg.test(value)) {
        ElMessage({
            type: 'warning',
            message: '请输入大于0的正整数'
        });
        // 清空无效输入
        ruleForm.quantity = '';
    }
};

// 原价失焦验证
const validateOldPriceInput = () => {
    const value = ruleForm.old_price;
    const reg = /^\d+(\.\d{1,2})?$/;

    if (value && (!reg.test(value) || parseFloat(value) <= 0)) {
        ElMessage({
            type: 'warning',
            message: '请输入大于0的数字'
        });
        // 清空无效输入
        ruleForm.old_price = '';
    }
};

// 现价失焦验证
const validatePriceInput = () => {
    const value = ruleForm.price;
    const reg = /^\d+(\.\d{1,2})?$/;

    if (value && (!reg.test(value) || parseFloat(value) <= 0)) {
        ElMessage({
            type: 'warning',
            message: '请输入大于0的数字'
        });
        // 清空无效输入
        ruleForm.price = '';
    }
};
</script>
<style>
/* 页面样式定义 */
.text {
    font-size: 14px;
}

.item {
    margin-bottom: 18px;
}

.clearfix:before,
.clearfix:after {
    display: table;
    content: '';
}

.clearfix:after {
    clear: both;
}

.box-card {
    display: flex;
    height: 300px;
    width: 90%;
}

.handle {
    display: flex;
    align-items: center;
    justify-content: center;
}

.paging {
    display: flex;
    justify-content: center;
    margin-top: 10px;
    height: 70px;
}

.flex {
    display: flex;
    align-items: center;
    padding-bottom: 10px;
}

.flexBox {
    display: flex;
    width: 100%;
    align-items: center;
}

.el-upload-list--picture-card {
    flex-wrap: nowrap !important;
}

.el-upload-list--picture-card {
    --el-upload-list-picture-card-size: 100px;
    display: inline-flex;
    flex-wrap: wrap;
    margin: 0;
}

.el-upload--picture-card {
    --el-upload-picture-card-size: 99px;
    align-items: center;
    background-color: var(--el-fill-color-lighter);
    border: 1px dashed var(--el-border-color-darker);
    border-radius: 6px;
    box-sizing: border-box;
    cursor: pointer;
    display: inline-flex;
    height: var(--el-upload-picture-card-size);
    justify-content: center;
    vertical-align: top;
    width: var(--el-upload-picture-card-size);
}

.el-date-range-picker__content {
    box-sizing: border-box;
    float: left;
    margin: 0;
    padding: 16px;
    width: 38%;
}

/* 自定义数字输入框样式 */
.custom-number-input {
    display: flex;
    align-items: center;
    width: 120px;
}

.custom-number-input button {
    width: 53px;
    height: 38px;
    border: 1px solid #dcdfe6;
    background-color: #f5f7fa;
    color: #606266;
    cursor: pointer;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 14px;
    user-select: none;
}

.custom-number-input button:hover {
    background-color: #e4e7ed;
}

.custom-number-input button:first-child {
    border-radius: 4px 0 0 4px;
}

.custom-number-input button:last-child {
    border-radius: 0 4px 4px 0;
}

.custom-number-input input {
    flex: 1;
    height: 38px;
    border: 1px solid #dcdfe6;
    border-left: none;
    border-right: none;
    text-align: center;
    padding: 0 5px;
    font-size: 14px;
    outline: none;
    width: 80px;
}

.custom-number-input input:focus {
    border-color: #409eff;
    box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.1);
}

/* 提取的内联样式 */
.container-padding {
    padding: 10px;
}

.category-title {
    width: 220px;
}

.search-input {
    width: 220px;
}

.date-picker-container {
    margin-left: 20px;
}

.button-group {
    display: flex;
}

.product-image {
    width: 40px;
    height: 40px;
}

.edit-btn {
    color: rgba(64, 158, 255, 1);
    cursor: pointer;
}

.delete-btn {
    color: red;
    cursor: pointer;
}

.handle-separator {
    width: 10px;
}

.form-container {
    padding: 10px;
}

.form-card {
    width: 96%;
    margin-left: 2%;
    margin-top: 1%;
    position: relative;
    height: auto;
}

.form-title {
    padding: 10px;
}

.divider {
    width: 100%;
    height: 1px;
    background-color: rgba(195, 195, 195, 1);
}

.form-content {
    margin-top: 20px;
    margin-left: 100px;
}

.form-row {
    width: 100%;
    display: flex;
}

.form-column {
    width: 48%;
}

.right-column {
    padding-left: 30px;
}

.form-item {
    width: 90%;
}

.image-upload {
    margin-top: 15px;
}

.form-actions {
    margin-top: 10px;
    margin-left: 80%;
}

.dialog-message {
    font-size: 16px;
    padding-bottom: 20px;
}

.dialog-footer {
    display: flex;
    justify-content: end;
}
</style>